<style lang="less" scoped>
  .f-w70 {
    width: 70%;
  }

  .f-w80 {
    width: 80%;
  }

  .f-w50 {
    width: 50%;
  }

  .el-mw {
    width: 25%;
    margin-left: 20px;
  }

  .el-form-item {
    margin-bottom: 18px;
  }
</style>

<template>
  <div>
    <search-bar more-display>
    <el-form ref="searchFreightContractForm" label-position="right" :model="searchFreightContractForm"
             label-width="120px">
      <el-row :span="24">
        <el-col :span="8">
          <el-form-item  label="运价合同名称" prop="name_LIKE">
            <el-input v-model="searchFreightContractForm.name_LIKE"
                      placeholder="请输入运价合同名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签约方名称" prop="signatoryId_EQ">
            <el-select v-model="searchFreightContractForm.signatoryId_EQ"
                       filterable
                       remote
                       :remote-method="searchMemberUsers"
                       placeholder="请选择签约方">
              <el-option v-for="(memberUser,index) in memberUsers"
                         :label="memberUser.realName"
                         :value="memberUser.userId" :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同组织" prop="contractOrganizationId_LIKE">
            <el-cascader
              placeholder="请选择合同组织" style="width: 100%"
              :options="$store.state.initOrganizations"
              :props="{label: 'name',value: 'id'}"
              change-on-select
              v-model="searchFreightContractForm.contractOrganizationId_LIKE"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :span="24">
        <el-col :span="8">
          <el-form-item  label="发布状态" prop="status_EQ">
            <el-select v-model="searchFreightContractForm.status_EQ"
                       filterable placeholder="请选择发布状态">
              <el-option
                v-for="(orderSource,index) in $store.getters.TARIFF_RELEASE_STATUS"
                :label="orderSource.cnDictValname"
                :value="orderSource.dictVal" :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生效日期" prop="operativeDate">
            <el-date-picker
                            v-model="searchFreightContractForm.operativeDate"
                            type="daterange"
                            placeholder="选择日期范围">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item  label="失效日期" prop="loseEfficacyDate">
            <el-date-picker
                            v-model="searchFreightContractForm.loseEfficacyDate"
                            type="daterange"
                            placeholder="选择日期范围">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    </search-bar>
    <div class="f-mt f-wa">
      <el-button type="primary" class="f-wa" @click="createFreightContractFormDialogClick">新增
      </el-button>
      <el-button type="primary" class="f-wa f-fr f-ml10 f-mr20 f-mb10"
                 @click="resetObjNull()">重置
      </el-button>
      <el-button type="primary" class="f-wa f-fr f-ml10 " @click="searchFreightContract">查询</el-button>
    </div>

    <el-table :data="searchFreightContractTableData" highlight-current-row border max-height="660">
      <el-table-column prop="contractNumber" label="合同编号" width="200">
      </el-table-column>
      <el-table-column prop="name" label="运价合同名称" width="200">
      </el-table-column>
      <el-table-column prop="signatoryName" label="签约方" width="160">
      </el-table-column>
      <el-table-column prop="contractOrganizationName" label="合同组织" width="150">
      </el-table-column>
      <el-table-column prop="createDate" label="创建日期" width="140">
      </el-table-column>
      <el-table-column prop="operativeDate" label="生效日期" width="180">
      </el-table-column>
      <el-table-column prop="loseEfficacyDate" label="失效日期" width="180">
      </el-table-column>
      <el-table-column prop="statusName" label="发布状态" width="120">
      </el-table-column>
      <el-table-column label="操作" width="310">
        <template slot-scope="scope">
          <!--待提交-->
          <el-button  type="primary" class="f-mt10 f-mb10 f-ml5"
                     v-if="scope.row.status===112001001"
                     @click="changeStatus(scope.row.id, 112001002,'提交审核')">提交审核
          </el-button>
          <el-button  type="primary" class="f-ml5" v-if="scope.row.status===112001001"
                     @click="freightContractDetailPage(scope.row.id)">维护运价
          </el-button>
          <el-button  type="primary" class="f-ml5" v-if="scope.row.status===112001001"
                     @click="modifFreightContractDialog(scope.row)">编辑
          </el-button>
          <el-button  type="danger" class="f-mb10 f-ml5" v-if="scope.row.status===112001001"
                     @click="deleteFreight(scope.row.id)">删除
          </el-button>
          <!--待审核-->
          <el-button  type="primary" class="f-ml5" v-if="scope.row.status===112001002"
                     @click="freightContractDetailPage(scope.row.id)">明细
          </el-button>
          <el-button  type="primary" class="f-ml5" v-if="scope.row.status===112001002"
                     @click="changeStatus(scope.row.id, 112001003,'发布')">发布
          </el-button>
          <el-button  type="warning" class="f-ml5" v-if="scope.row.status===112001002"
                     @click="changeStatus(scope.row.id, 112001001,'撤销')">撤销审核
          </el-button>
          <!--已发布 | 已过期 | 已禁用-->
          <el-button  type="primary" class="f-ml5"
                     v-if="scope.row.status===112001003||scope.row.status===112001005||scope.row.status===112001006"
                     @click="freightContractDetailPage(scope.row.id)">明细
          </el-button>
          <el-button  type="warning" class="f-ml5"
                     v-if="scope.row.status===112001003"
                     @click="changeStatus(scope.row.id, 112001002,'撤销')">撤销发布
          </el-button>
          <!--已启用-->
          <el-button  type="primary" v-if="scope.row.status===112001004" class="f-ml5"
                     @click="freightContractDetailPage(scope.row.id)">明细
          </el-button>
          <el-button  type="primary" v-if="scope.row.status===112001004" class="f-ml5"
                     @click="changeStatus(scope.row.id, 112001006,'禁用')">禁用
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>

    <!--新增/修改dialog-->
    <el-dialog title="新增运价合同" :visible.sync="searchFreightContractDialog" size="tiny">
      <el-form label-width="110px" ref="freightContractForm" :model="freightContractForm"
               :rules="freightContractFormRules">
        <el-form-item label="运价合同名称" prop="name">
          <el-input v-model="freightContractForm.name" class="f-w80"></el-input>
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input v-model="freightContractForm.contractNumber" class="f-w80"></el-input>
        </el-form-item>
        <el-form-item label="签约方" prop="signatoryId">
          <el-select v-model="freightContractForm.signatoryId"
                     class="f-w80"
                     filterable
                     remote
                     :remote-method="searchMemberUsers"
                     placeholder="请选择签约方">
            <el-option v-for="(memberUser,index) in memberUsers"
                       :label="memberUser.realName"
                       :value="memberUser.userId" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同组织" prop="contractOrganizationIds">
          <el-cascader
            placeholder="请选择合同组织"
            class="f-w80"
            :options="$store.state.initOrganizations"
            :props="{label: 'name',value: 'id'}"
            change-on-select
            v-model="freightContractForm.contractOrganizationIds"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="生效时间" prop="operativeDate">
          <el-date-picker
            class="f-w80"
            v-model="freightContractForm.operativeDate"
            type="datetime"
            placeholder="选择生效时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="失效时间" prop="loseEfficacyDate">
          <el-date-picker
            class="f-w80"
            v-model="freightContractForm.loseEfficacyDate"
            type="datetime"
            placeholder="选择失效时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结算方式" prop="paymentType">
          <el-select class="f-w50" v-model.number="freightContractForm.paymentType"
                     placeholder="请选择结算方式">
            <el-option v-for="(receivableType,index) in $store.getters.PAY_WAY"
                       :label="receivableType.cnDictValname"
                       :value="receivableType.dictVal" :key="index">
            </el-option>
          </el-select>
          <el-input v-model="freightContractForm.paymentRatio"
                    :disabled="freightContractForm.paymentType === 102002001||freightContractForm.paymentType === 102002002||freightContractForm.paymentType === 102002006||freightContractForm.paymentType === ''"
                    placeholder="月结费率" class="el-mw"></el-input>
        </el-form-item>
        <el-form-item label="保价运输费率" prop="supportRatio">
          <el-input v-model="freightContractForm.supportRatio" class="f-w80"
                    placeholder="请输入保价运输费率"></el-input>
        </el-form-item>
        <el-form-item label="代收货款费率" prop="collectRatio">
          <el-input v-model="freightContractForm.collectRatio" class="f-w80"
                    placeholder="请输入代收货款费率率"></el-input>
        </el-form-item>
        <el-form-item label="回单服务" prop="receipt">
          <el-select class="f-w50" v-model="freightContractForm.receipt"
                     placeholder="请选择回单服务">
            <el-option v-for="(receiptType,index) in receiptTypes"
                       :label="receiptType.cnDictValname"
                       :value="receiptType.dictVal" :key="index">
            </el-option>
          </el-select>
          <el-input v-model="freightContractForm.receiptValue" class="el-mw"></el-input>
        </el-form-item>
        <el-form-item label="发票抬头" prop="taxsheetTitleId">

          <el-select
            class="f-w80"
            v-model="freightContractForm.taxsheetTitleId"
            remote
            :remote-method="mySearchTaxsheet"
            @change="searchTaxsheet"
            filterable
            placeholder="请选择">
            <el-option v-for="(mu,index) in searchTaxshhetTest" :label="mu.taxsheetTitle"
                       :value="mu.id" :key="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票类型">
          <el-input :disabled="true" v-model="freightContractForm.invoiceName" class="f-w80"></el-input>
        </el-form-item>
        <el-form-item label=" 备 注 ">
          <el-input type="textarea" v-model="freightContractForm.remark" class="f-w80"
                    auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="searchFreightContractDialog = false">取 消</el-button>
        <el-button type="primary" @click="createfreightContractForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { searchInvoiceManageByFreightContract } from '../../api/meb-user/TaxsheetTitle.js';
import { isEmpty, resetObjNull, toFilters, getSelectObect } from '../../lib/util.js';
import {
  searchFreightContracts,
  saveFreightContract,
  changeStatus,
  deleteFreightContract
} from '../../api/freight/freightContractApi.js';
import { getMemberUsers } from '../../api/customer/maintain.js';
import { getDictEntity } from '../../api/system/Dict.js';
export default{
  data () {
    return {
      searchTaxshhetTest: [],
      token: this.$store.state.token,
      stowagesCores: [],
      searchFreightContractDialog: false,
      /**
         * 检索FORM
         */
      searchFreightContractForm: {
        name_LIKE: '',
        signatoryId_EQ: '',
        contractOrganizationId_LIKE: [],
        status_EQ: '',
        operativeDate: '',
        loseEfficacyDate: ''
      },
      controlCenter: [],
      /**
         * 运价合同新增/修改FORM
         */
      organizationId: [],
      freightContractForm: {
        name: '',
        contractNumber: '',
        taxsheetTitleId: '',
        taxsheetTitleName: '',
        signatoryId: '',
        contractOrganizationIds: [],
        contractOrganizationId: '',
        operativeDate: '',
        loseEfficacyDate: '',
        operativeDateTemp: '',
        loseEfficacyDateTemp: '',
        paymentType: '',
        paymentRatio: '',
        supportRatio: '',
        collectRatio: '',
        receipt: '',
        receiptValue: '',
        invoice: '',
        invoiceValue: '',
        remark: ''
      },
      freightContractFormRules: {
        name: [
          {required: true, message: '请输入运价合同名称', trigger: 'change'}
        ],
        contractNumber: [
          {required: true, message: '请输入运价合同编号', trigger: 'change'}
        ],
        signatoryId: [
          {required: true, message: '请选择签约方', trigger: 'change'}
        ],
        contractOrganizationIds: [
          {required: true, type: 'array', message: '请选择合同组织', trigger: 'change'}
        ],
        operativeDate: [
          {required: true, type: 'date', message: '选择生效时间', trigger: 'change'}
        ],
        loseEfficacyDate: [
          {required: true, type: 'date', message: '选择失效时间', trigger: 'change'}
        ],
        paymentType: [
          {required: true, type: 'number', message: '请选择结算方式', trigger: 'change'}
        ]
      },
      searchFreightContractTableData: [],
      invoiceTypes: [],
      receiptTypes: [],
      memberUsers: [],
      total: 0,
      currentPage: 1,
      pageSize: 10
    };
  },
  methods: {
    // 发票抬头赋值
    searchTaxsheet (event) {
      let datas = getSelectObect(this.freightContractForm.taxsheetTitleId, 'id', this.searchTaxshhetTest);
      this.freightContractForm.invoice = datas.taxsheetType;
      this.freightContractForm.invoiceName = datas.typeName;
      this.freightContractForm.taxsheetTitleName = datas.taxsheetTitle;
    },
    // 开票抬头搜索
    mySearchTaxsheet (event) {
      searchInvoiceManageByFreightContract({
        filters: 'EQ_userId=' + this.freightContractForm.signatoryId,
        sorts: '',
        size: '15',
        page: '1'
      }).then((res) => {
        this.searchTaxshhetTest = res.data.detailModelList;
      });
    },
    freightContractDetailPage (id) {
      this.$router.push('/freight_manage/freightContractDetail/' + id);
    },
    searchFreightContract () {
      this.initSearchFreightContracts(toFilters(this.searchFreightContractForm));
    },
    resetObjNull () {
      resetObjNull(this.searchFreightContractForm);
    },
    modifFreightContractDialog (row) {
      this.searchFreightContractDialog = true;
      if (this.$refs.freightContractForm) {
        this.$refs.freightContractForm.resetFields();
      }
      //        this.organizationId = row.contractOrganizationId.split(',');
      row.contractOrganizationIds = row.contractOrganizationId.split(',');
      this.freightContractForm = Object.assign({
        name: '',
        contractNumber: '',
        signatoryId: '',
        contractOrganizationId: [],
        operativeDate: '',
        loseEfficacyDate: '',
        paymentType: '',
        paymentRatio: '',
        supportRatio: '',
        collectRatio: '',
        receipt: '',
        receiptValue: '',
        invoice: '',
        invoiceValue: '',
        remark: ''
      }, row);
      //        this.organizationId = [];
      //        this.freightContractForm.contractOrganizationId = [];
    },
    deleteFreight (freightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        type: 'error'
      }).then(() => {
        deleteFreightContract(freightId).then((res) => {
          if (res.data.successFlg) {
            this.$message.success('删除成功');
            this.initSearchFreightContracts('');
          } else {
            this.$message.error(res.data.errorMsg);
          }
        }).catch(function (error) {
          this.$message.error('删除失败');
          console.log(error);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    changeStatus (id, status, msg) {
      this.$confirm('更改运价文件状态, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        changeStatus(id, status).then((res) => {
          if (res.data.successFlg) {
            this.$message.success(msg + '成功');
            this.initSearchFreightContracts();
          }
        }).catch(function (error) {
          this.$message.error(msg + '失败');
          console.log(error);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消' + msg
        });
      });
    },

    createfreightContractForm () {
      console.log(this.freightContractForm.operativeDate);
      this.freightContractForm.operativeDate = new Date(this.freightContractForm.operativeDate);
      this.freightContractForm.loseEfficacyDate = new Date(this.freightContractForm.loseEfficacyDate);
      this.$refs['freightContractForm'].validate((freightContractFormValid) => {
        this.freightContractForm.operativeDateTemp = this.freightContractForm.operativeDate.Format('yyyy-MM-dd hh:mm:ss');
        this.freightContractForm.loseEfficacyDateTemp = this.freightContractForm.loseEfficacyDate.Format('yyyy-MM-dd hh:mm:ss');
        if (freightContractFormValid) {
          this.freightContractForm.contractOrganizationId = this.freightContractForm.contractOrganizationIds.join(',');
          saveFreightContract(this.freightContractForm).then((res) => {
            let data = res.data;
            if (data.successFlg) {
              this.searchFreightContractDialog = false;
              this.initSearchFreightContracts('');
            }
          });
        }
      });
    },
    createFreightContractFormDialogClick () {
      this.searchFreightContractDialog = true;
      if (this.$refs.freightContractForm) {
        this.$refs.freightContractForm.resetFields();
      }
      this.organizationId = [];
      for (let p in this.freightContractForm) {
        if (this.freightContractForm[p] instanceof Array) {
          this.freightContractForm[p] = [];
        } else {
          this.freightContractForm[p] = null;
        }
      }
      this.freightContractForm.paymentType = null;
    },
    initSearchFreightContracts (filters) {
      searchFreightContracts({
        page: this.currentPage,
        size: this.pageSize,
        filters: filters,
        sorts: '-createDate'
      }).then((res) => {
        if (res.data.successFlg) {
          this.searchFreightContractTableData = res.data.detailModelList;
          this.currentPage = res.data.currPage;
          this.total = res.data.totalCount;
          this.pageSize = res.data.pageSize;
        }
      });
    },

    searchMemberUsers (val) {
      let filters = isEmpty(val) ? 'logicStatus=111002002;status=111002001' : 'logicStatus=111002002;status=111002001;realName?' + val + ' g1';
      getMemberUsers({
        token: this.token,
        filters: filters,
        sorts: '',
        size: '15',
        page: '1'
      }).then((res) => {
        this.memberUsers = res.data.detailModelList;
        this.mySearchTaxsheet();
      });
    },
    searchInvoiceTypes () {
      let filters = 'dictVal=101002005,101002006,101002007';
      getDictEntity({token: this.token, filters: filters}).then((res) => {
        this.invoiceTypes = res.data.detailModelList;
      });
    },
    searchReceiptTypes (val) {
      let filters = 'dictVal=101002003,101002004';
      getDictEntity({token: this.token, filters: filters}).then((res) => {
        this.receiptTypes = res.data.detailModelList;
      });
      if (val === 101002004) {

      }
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchFreightContract();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchFreightContract();
    }
  },
  // 初始化js
  mounted () {
    this.initSearchFreightContracts('');
    this.searchReceiptTypes();
    this.searchInvoiceTypes();
    this.searchMemberUsers();
    this.$store.commit('initDict');
    this.$store.commit('initOrganizations');
  }
};
</script>
